from django.urls import re_path
from stark.service.s1 import StarkHandler
from stark.service.s1 import choice_display
from app_main.forms.for_stark import PayRecordModelForm, MorePayRecordModelForm
from app_main import models


class PayRecordHandler(StarkHandler):
    model_form_class = PayRecordModelForm

    list_display = [
        choice_display('缴费类型', 'pay_type'),
        'money',
        'to_class',
        'consultant',
        choice_display('确认状态', 'confirm_status')
    ]

    def get_urls(self):
        patterns = [
            re_path('list/(?P<cid>\d+)/$', self.wrapper(self.list_view), name=self.get_list_url_name),
            re_path('add/(?P<cid>\d+)/$', self.wrapper(self.add_view), name=self.get_add_url_name)
        ]

        patterns.extend(self.extra_urls())

        return patterns

    def get_query_set(self, request, *args, **kwargs):
        current_c_id = kwargs.get('cid')
        current_user_id = request.session['user_info']['id']
        q_set = self.model_class.objects.filter(customer_id=current_c_id, consultant_id=current_user_id)
        return q_set

    def save(self, request, form_obj, is_update, *args, **kwargs):
        current_c_id = kwargs.get('cid')
        current_user_id = request.session['user_info']['id']

        obj_exit = models.Customer.objects.filter(id=current_c_id, consultant_id=current_user_id).exists()
        if not obj_exit:
            return

        form_obj.instance.customer_id = current_c_id
        form_obj.instance.consultant_id = current_user_id
        form_obj.save()

        # 当第一次为客户创建费用记录时，在 Student表中创建数据
        s_obj = models.Student.objects.filter(customer_id=current_c_id).first()
        c_list = form_obj.cleaned_data['to_class']  # c_list是一个 object
        if not s_obj:
            customer_id = current_c_id
            qq = form_obj.cleaned_data['qq']
            mobile = form_obj.cleaned_data['mobile']
            emergency_contact = form_obj.cleaned_data['emergency_contact']

            s_object = models.Student.objects.create(customer_id=customer_id, qq=qq, mobile=mobile,
                                                     emergency_contact=emergency_contact)
            s_object.class_list.add(c_list.id)
        else:
            s_obj.class_list.add(c_list.id)

    def get_model_form_class(self, add_or_edit, request, *args, **kwargs):
        c_id = kwargs.get('cid')
        obj_exit = models.Student.objects.filter(customer_id=c_id).exists()

        if obj_exit:
            return PayRecordModelForm
        else:
            return MorePayRecordModelForm
